package com.zzr.zzrbackend.service.Impl;


import com.zzr.zzrbackend.config.JwtInterceptor;
import com.zzr.zzrbackend.mapper.*;
import com.zzr.zzrbackend.pojo.domain.*;
import com.zzr.zzrbackend.pojo.dto.CommonResult;
import com.zzr.zzrbackend.pojo.dto.param.*;
import com.zzr.zzrbackend.pojo.dto.result.*;
import com.zzr.zzrbackend.service.HomeInterfaceService;
import com.zzr.zzrbackend.util.Recommend;
import com.zzr.zzrbackend.util.TokenUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class HomeInterfaceServiceImpl implements HomeInterfaceService {
    @Resource
    private JwtInterceptor jwtInterceptor;
    @Resource
    HttpServletRequest request;
    @Resource
    HomeInterfaceMapper homeInterfaceMapper;
    @Resource
    ContentInfoMapper contentInfoMapper;
    @Resource
    BookTextMapper bookTextMapper;
    @Resource
    BookDetailMapper bookDetailMapper;
    @Resource
    OriginalAudioMapper originalAudioMapper;
    @Resource
    TrackRecordTimeMapper trackRecordTimeMapper;
    @Resource
    private RelationMapper relationMapper;
    @Resource
    private DisabuseRecordMapper disabuseRecordMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private BookScoreMapper bookScoreMapper;

    @Override
    public CommonResult<InterfaceResult> childHome(InterfaceParam interfaceParam) {

        //遍历content表中的精选内容
        List<HomeInterface> homeInterface = homeInterfaceMapper.selectAll();

        //遍历content表中的轮播图
        List<HomeInterface> homeInterfacePicture = homeInterfaceMapper.selectSlideshow();

        if (homeInterface.size() == 0 && homeInterfacePicture.size() == 0) {
            return CommonResult.fail("数据库异常");
        }

        //封装精选内容信息
        List<HomeInfoParam> homeInfoParamList = new ArrayList<>();

        for (HomeInterface temp : homeInterface) {

            //封装HomeInfoParam成员信息
            HomeInfoParam homeInfoParam = new HomeInfoParam();
            homeInfoParam.setId(temp.getId());
            homeInfoParam.setName(temp.getName());
            homeInfoParam.setType(temp.getType());
            homeInfoParam.setTheme(temp.getTheme());
            homeInfoParam.setCoverPictureUrl(temp.getCoverPictureUrl());

            //模糊查询
            if (interfaceParam.getSearchWord() != null) {
                String keyword = interfaceParam.getSearchWord();
                if (homeInfoParam.getName().contains(keyword) || homeInfoParam.getName().equals(keyword)) {
                    homeInfoParamList.add(homeInfoParam);
                }
            } else {
                homeInfoParamList.add(homeInfoParam);
            }
        }

        //封装轮播图信息
        List<HomeInfoParam> homeInfoParamPictureList = new ArrayList<>();

        for (HomeInterface temp : homeInterfacePicture) {

            //封装HomeInfoParam成员信息
            HomeInfoParam homeInfoPictureParam = new HomeInfoParam();
            homeInfoPictureParam.setId(temp.getId());
            homeInfoPictureParam.setName(temp.getName());
            homeInfoPictureParam.setType(temp.getType());
            homeInfoPictureParam.setTheme(temp.getTheme());
            homeInfoPictureParam.setCoverPictureUrl(temp.getCoverPictureUrl());

            //模糊查询
            if (interfaceParam.getSearchWord() != null) {
                String keyword = interfaceParam.getSearchWord();
                if (homeInfoPictureParam.getName().contains(keyword) || homeInfoPictureParam.getName().equals(keyword)) {
                    homeInfoParamPictureList.add(homeInfoPictureParam);
                }
            } else {
                homeInfoParamPictureList.add(homeInfoPictureParam);
            }
        }

        //封装返回类
        InterfaceResult interfaceResult = new InterfaceResult();
        interfaceResult.setTotal(homeInfoParamList.size() + homeInfoParamPictureList.size());
        interfaceResult.setHomeInfoParamList(homeInfoParamList);
        interfaceResult.setHomeInfoPictureParamList(homeInfoParamPictureList);

        return CommonResult.success(interfaceResult);
    }

    @Override
    public CommonResult<HomeListResult> childList(HomeListParam homeListParam) {

        Integer contentId = homeListParam.getContentId();

        if (contentId == null) {
            return CommonResult.fail("数据库异常");
        }

        List<ContentInfo> contentInfoList = contentInfoMapper.selectAllById(contentId);

        if (contentInfoList.size() == 0) {
            return CommonResult.fail("数据库异常");
        }

        List<HomeListContentParam> homeListContentParamList = new ArrayList<>();

        for (ContentInfo temp : contentInfoList) {

            //封装 HomeListContentParam成员信息
            HomeListContentParam homeListContentParam = new HomeListContentParam();
            homeListContentParam.setId(temp.getId());
            homeListContentParam.setHeadName(temp.getHeadName());
            homeListContentParam.setContentId(temp.getContentId());
            homeListContentParam.setOrder(temp.getOrder());
            homeListContentParam.setOriginalAudioId(temp.getOriginalAudioId());
            homeListContentParam.setAiAudioId(temp.getAiAudioId());

            homeListContentParamList.add(homeListContentParam);

        }

        HomeListResult homeListResult = new HomeListResult();
        homeListResult.setTotal(homeListContentParamList.size());
        homeListResult.setHomeListContentParamList(homeListContentParamList);

        return CommonResult.success(homeListResult);

    }

    @Override
    public CommonResult<BookTextResult> bookText(BookTextParam bookTextParam) {
        BookText bookText = bookTextMapper.selectByIdAndOrder(bookTextParam.getContentId(), bookTextParam.getOrder());
        if (bookText == null) {
            return CommonResult.fail("数据库异常");
        }

        HomeInterface homeInterface = bookDetailMapper.selectPicById(bookText.getContentId());
        if (homeInterface == null) {
            return CommonResult.fail("数据库异常");
        }

        ContentInfo contentInfo = contentInfoMapper.selectTitle(bookTextParam.getContentId(), bookTextParam.getOrder());
        if (contentInfo == null) {
            return CommonResult.fail("数据库异常");
        }

        BookTextResult bookTextResult = new BookTextResult();
        bookTextResult.setMainText(bookText.getMainText());
        bookTextResult.setPicUrl(homeInterface.getCoverPictureUrl());
        bookTextResult.setTitle(contentInfo.getHeadName());

        return CommonResult.success(bookTextResult);
    }

    @Override
    public CommonResult<BookTextResult> bookDetail(HomeListParam homeListParam) {
        BookDetail bookDetail = bookDetailMapper.selectById(homeListParam.getContentId());
        if (bookDetail == null) {
            return CommonResult.fail("数据库异常");
        }

        HomeInterface homeInterface = bookDetailMapper.selectPicById(homeListParam.getContentId());

        if (homeInterface == null) {
            return CommonResult.fail("数据库异常");
        }

        BookTextResult bookTextResult = new BookTextResult();
        bookTextResult.setMainText(bookDetail.getStoryDetail());
        bookTextResult.setStoryPlot(bookDetail.getStoryPlot());
        bookTextResult.setTitle(homeInterface.getName());
        bookTextResult.setPicUrl(homeInterface.getCoverPictureUrl());
        return CommonResult.success(bookTextResult);
    }

    @Override
    public CommonResult<BookPlayResult> bookPlay(BookPlayParam bookPlayParam) {
        Integer userId = jwtInterceptor.getUserId(request);

        ContentInfo contentInfo = contentInfoMapper.selectAll(bookPlayParam.getContentId(),
                bookPlayParam.getOriginalAudioId());
        if(null == contentInfo){
            return CommonResult.fail("无此章节的音频");
        }
        if (contentInfo.getOrder() == null) {
            return CommonResult.fail_getMessage("无此章节");
        }

        String writer = homeInterfaceMapper.selectWriterById(bookPlayParam.getContentId());

        OriginalAudio originalAudio = originalAudioMapper.selectById(bookPlayParam.getOriginalAudioId());

        if (originalAudio == null) {
            return CommonResult.fail("数据库异常");
        }

        //添加当前播放的时间戳
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Long endTime = timestamp.getTime() / 1000;

        TrackRecordTime trackRecordTime = new TrackRecordTime();
        trackRecordTime.setUserId(userId);
        trackRecordTime.setContentId(bookPlayParam.getContentId());
        trackRecordTime.setOrder(contentInfo.getOrder());
        trackRecordTime.setTime(endTime);

        trackRecordTimeMapper.insert(trackRecordTime);

        BookPlayResult bookPlayResult = new BookPlayResult();
        bookPlayResult.setStoryName(contentInfo.getHeadName());
        bookPlayResult.setWriter(writer);
        bookPlayResult.setAudioUrl(originalAudio.getAudioUrl());

        return CommonResult.success(bookPlayResult);
    }

    @Override
    public CommonResult<HomeInformationResult> getHomeInformation(HttpServletRequest request) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer permission = (Integer) claims.get("permission");
        Integer userId = (Integer) claims.get("id");
        HomeInformationResult homeInformationResult = new HomeInformationResult();
        homeInformationResult.setHelloMessage(getNowTimeState() + "好!\n欢迎来到护苗");
        List<String> disabuseList = new ArrayList<>();
        if (permission == 2) {
            //家长
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
            if (userInfo != null) {
                homeInformationResult.setHeadUrl(userInfo.getHeadPicUrl());
            } else {
                homeInformationResult.setHeadUrl("http://hbws.file.yuleng.top/image/parent_default.png");
            }
            List<Integer> integers = relationMapper.selectChildIdByParentId(userId);
            for (Integer childId : integers) {
                DisabuseRecord latestDisabuseByChildId = disabuseRecordMapper.getLatestDisabuseByChildId(childId);
                if (latestDisabuseByChildId != null) {
                    String userName = userMapper.selectUserNameById(childId);
                    disabuseList.add(userName + "提出的问题:" + latestDisabuseByChildId.getQuestion());
                }
            }
            homeInformationResult.setDisabuseList(disabuseList);
            return CommonResult.success(homeInformationResult);
        } else if (permission == 3) {
            //志愿者
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
            if (userInfo != null) {
                homeInformationResult.setHeadUrl(userInfo.getHeadPicUrl());
            } else {
                homeInformationResult.setHeadUrl("http://hbws.file.yuleng.top/image/zhiyuanzhe_default.png");
            }
            List<DisabuseRecord> disabuseRecords = disabuseRecordMapper.selectAllDisabuseList();
            for (DisabuseRecord disabuseRecord : disabuseRecords) {
                String userName = userMapper.selectUserNameById(disabuseRecord.getChildId());
                disabuseList.add(userName + "提出的问题:" + disabuseRecord.getQuestion());
            }
            homeInformationResult.setDisabuseList(disabuseList);
            return CommonResult.success(homeInformationResult);
        } else {
            return CommonResult.userAuthError("用户权限错误");
        }
    }

    @Override
    public CommonResult<InterfaceResult> recommendBook(HttpServletRequest request) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");

        Recommend recommend = new Recommend();
        List<String> snList = recommend.getRecommend(userId);
//        System.out.println(snList.get(0));

        if(snList == null){
            return CommonResult.fail("数据库异常");
        }
        //遍历content表中的精选内容
        List<HomeInterface> homeInterfaceList = new ArrayList<>();
        for(String s: snList){
            int id = Integer.parseInt(s.trim());
            HomeInterface homeInterface = homeInterfaceMapper.selectById(id);
            homeInterfaceList.add(homeInterface);
        }

        //遍历content表中的轮播图
        List<HomeInterface> homeInterfacePicture = homeInterfaceMapper.selectSlideshow();

        if (homeInterfaceList.size() == 0 && homeInterfacePicture.size() == 0) {
            return CommonResult.fail("数据库异常");
        }

        //封装精选内容信息
        List<HomeInfoParam> homeInfoParamList = new ArrayList<>();

        for (HomeInterface temp : homeInterfaceList) {

            //封装HomeInfoParam成员信息
            HomeInfoParam homeInfoParam = new HomeInfoParam();
            homeInfoParam.setId(temp.getId());
            homeInfoParam.setName(temp.getName());
            homeInfoParam.setType(temp.getType());
            homeInfoParam.setTheme(temp.getTheme());
            homeInfoParam.setCoverPictureUrl(temp.getCoverPictureUrl());

            homeInfoParamList.add(homeInfoParam);
        }

        //封装轮播图信息
        List<HomeInfoParam> homeInfoParamPictureList = new ArrayList<>();

        for (HomeInterface temp : homeInterfacePicture) {

            //封装HomeInfoParam成员信息
            HomeInfoParam homeInfoPictureParam = new HomeInfoParam();
            homeInfoPictureParam.setId(temp.getId());
            homeInfoPictureParam.setName(temp.getName());
            homeInfoPictureParam.setType(temp.getType());
            homeInfoPictureParam.setTheme(temp.getTheme());
            homeInfoPictureParam.setCoverPictureUrl(temp.getCoverPictureUrl());

            homeInfoParamPictureList.add(homeInfoPictureParam);

        }

        //封装返回类
        InterfaceResult interfaceResult = new InterfaceResult();
        interfaceResult.setTotal(homeInfoParamList.size());
        interfaceResult.setHomeInfoParamList(homeInfoParamList);
        interfaceResult.setHomeInfoPictureParamList(homeInfoParamPictureList);

        return CommonResult.success(interfaceResult);

    }

    @Override
    public CommonResult<NoData> setScore(SetScoreParam setScoreParam) {
        Integer userId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(userId);
        Integer i = bookScoreMapper.insert(userId, setScoreParam.getScore(), setScoreParam.getContentId());
        if(i==0){
            return CommonResult.fail("评分失败");
        }
        if(user.getIsEvaluation()==0){
            userMapper.updateEvaluation(userId);
        }

        return CommonResult.success();
    }

    
    @Override
    public CommonResult<IsEvaluationResult> isEvaluation() {
        Integer userId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(userId);
        if(user==null){
            return CommonResult.fail("数据库异常");
        }
        IsEvaluationResult isEvaluationResult = new IsEvaluationResult();
        isEvaluationResult.setIsEvaluation(user.getIsEvaluation());
        return CommonResult.success(isEvaluationResult);
    }

    public String getNowTimeState() {
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String str = df.format(date);
        int a = Integer.parseInt(str);
        if (a >= 0 && a <= 6) {
            return "凌晨";
        }
        if (a > 6 && a < 12) {
            return "上午";
        }
        if (a >= 12 && a <= 13) {
            return "中午";
        }
        if (a > 13 && a <= 18) {
            return "下午";
        }
        if (a > 18 && a <= 24) {
            return "晚上";
        }
        return "你好";
    }
}
